import _ from 'lodash';
import { history } from 'umi';
import {getOriginalPath} from '@/utils/routeFormat'

const MenuModel = {
  namespace: 'menu',
  state: {
    pathname: '',
    crumbList: [],
    tagMenuList: [],
    routePathList: {},
  },
  effects: {
    *initRouteOption({ payload }, { put }) {
      // 当前只处理初始化逻辑（未处理更新逻辑2022-9-30）
      console.log('====Menu Model Init====');
      const { defaultUrl, currentPath, routePathList } = payload;
      const nextCrumbList = routePathList[currentPath] || [];
      const defaultMenuItem = _.last(routePathList[defaultUrl] || []);
      const currentMenuItem = _.last(nextCrumbList);
      const nextTagMenuList = defaultMenuItem
        ? _.concat(
            [defaultMenuItem],
            defaultUrl === currentPath ? [] : currentMenuItem ? [currentMenuItem] : [],
          )
        : [];
      yield put({
        type: 'updateMenuOpts',
        payload: {
          crumbList: nextCrumbList,
          tagMenuList: nextTagMenuList,
          routePathList,
        },
      });
    },
    *historyChange({ payload }, { put, select }) {
      // console.log('====路由切换====');
      const pathname = payload;
      yield put({ type: 'updateMenuOpts', payload: { pathname } });

      const originalPathname = getOriginalPath(pathname);
      if (originalPathname === pathname) {
        const [currentTagMenuList, currentRoutePathList] = yield select(({ menu }) => [
          menu.tagMenuList,
          menu.routePathList,
        ]);
        if (!_.isEmpty(currentRoutePathList)) {
          const nextCrumbList = currentRoutePathList[pathname] || [];
          const currentIndex = _.findIndex(currentTagMenuList, ({ path }) => path === pathname);
          if (currentIndex === -1) {
            const currentTagMenuItem = _.last(nextCrumbList);
            const nextTagMenuList = _.concat(
              currentTagMenuList,
              currentTagMenuItem ? [currentTagMenuItem] : [],
            );
            yield put({
              type: 'updateMenuOpts',
              payload: { crumbList: nextCrumbList, tagMenuList: nextTagMenuList },
            });
          } else {
            yield put({
              type: 'updateMenuOpts',
              payload: { crumbList: nextCrumbList },
            });
          }
        }
      }
    },
    *closeTagMenu({ payload }, { put, select }) {
      const [currentPathname, currentTagMenuList] = yield select(({ menu }) => [
        menu.pathname,
        menu.tagMenuList,
      ]);
      const pathIndex = _.findIndex(currentTagMenuList, ({ path }) => path === payload);
      if (pathIndex > -1) {
        const nextTagMenuList = [...currentTagMenuList];
        nextTagMenuList.splice(pathIndex, 1);
        yield put({ type: 'updateMenuOpts', payload: { tagMenuList: nextTagMenuList } });
        if (payload === getOriginalPath(currentPathname)) {
          const nextPath = (nextTagMenuList[pathIndex] || _.last(nextTagMenuList))?.path;
          if (nextPath) {
            history.push(nextPath);
          }
        }
      }
    },
  },
  reducers: {
    updateMenuOpts(state, action) {
      return {
        ...state,
        ..._.pick(action.payload, _.keys(state)),
      };
    },
    resetByLogout(state) {
      return {
        ...state,
        crumbList: [],
        tagMenuList: [],
        routePathList: {},
      };
    },
  },
};
export default MenuModel;
